package com.easy.dev.utils;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

public class WrapperUtils {
    public static QueryWrapper getWrapperByEntity(Object entity) {
        if (entity == null) {
            return null;
        }
        QueryWrapper wrapper = new QueryWrapper();
        Field[] fields = ClassUtils.getFields(entity.getClass());
        try {
            for (Field field : fields) {
                String name = field.getName();
                Object value = field.get(entity);
                wrapper.eq(ClassNameUtils.getUnderlineTableName(name), value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wrapper;
    }

    public static QueryWrapper getWrapperByParams(Map<String, Object> params, Class clazz) {
        if (params == null || params.size() == 0) {
            return null;
        }
        QueryWrapper wrapper = new QueryWrapper();
        params.forEach((key, value) -> {
            Field field = ClassUtils.getFieldByClassAndName(clazz, key);
            if (field != null) {
                String name = null;
                TableField tableField = field.getAnnotation(TableField.class);
                if (tableField != null) {
                    name = tableField.value();
                } else {
                    name = field.getName();
                }
                wrapper.eq(name, value);
            }
        });
        return wrapper;
    }

}
